<template>
  <el-dialog
    :title="title"
    :model-value="modelValue"
    width="30%"
    align-center
    draggable
    @close="onClose"
    style="border-radius: 10px; padding: 5px 10px"
  >
    <div style="color: red; margin-bottom: 10px" v-show="tipShow">
      ！注意：该导入操作为覆盖操作，非新增操作
    </div>
    <el-upload
      ref="uploadRef"
      :accept="fileType"
      :show-file-list="true"
      action=""
      :on-success="handleFileSuccess"
      :before-upload="handleFileBefore"
      :http-request="upload"
      :auto-upload="false"
      :limit="1"
      drag
    >
      <el-icon class="el-icon--upload">
        <upload-filled />
      </el-icon>
      <div class="el-upload__text">
        将文件拖到此处，或
        <em>点击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <span>仅允许导入{{ fileType }}格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
          >
            下载模板
          </el-link>
        </div>
      </template>
    </el-upload>
    <div style="display: flex; justify-content: flex-end">
      <el-button type="primary" @click="submit">上 传</el-button>
      <el-button @click="modelValue = false">取消</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits, ref, watch, nextTick } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import request from "@/service/request";

const uploadRef = ref();

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
  },
  title: {
    type: String,
    default: "文件上传",
  },
  url: {
    type: String,
    default: "",
  },
  fileType: {
    type: String,
    default: ".xlsx , .xls",
  },
  tipShow: {
    type: Boolean,
    default: false,
  },
});
const emits = defineEmits(["update:modelValue", "onSuccess", "onDownTemplate"]);

const submit = () => {
  uploadRef.value.submit();
};

const upload = (param) => {
  const formData = new FormData();
  formData.append("file", param.file);
  request
    .post(props.url, formData)
    .then((res) => {
      emits("onSuccess", res);
      uploadRef.value.clearFiles();
    })
    .catch((response) => {});
};

/** 文件上传成功处理 */
const handleFileSuccess = (res, file) => {
  if (res.status.error_code == 0) {
    emits("onSuccess");
  } else {
    // ElMessage.error(res.status.error_msg);
  }
};
/**文件上传之前 */
const handleFileBefore = (file) => {};
/**下载模板 */
const importTemplate = () => {
  emits("onDownTemplate");
};

/**
 * 关闭
 */
const onClose = () => {
  emits("update:modelValue", false);
};
</script>

<style lang="scss" scoped></style>
